package com.hxexp.weixin.mvc.login.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.constant.Errcode;
import com.hxexp.weixin.constant.WebAppVersion;
import com.hxexp.weixin.hpe.api.login.model.LoginResultBean;
import com.hxexp.weixin.mvc.login.service.LoginService;

/**
 * 登录控制器
 * @author li.jiang
 *
 */
@Controller
@RequestMapping(value="/login")
public final class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    private static final String LOGIN_INDEX_URI = "/login/index.do";
    private static final String TRAFFICLINE_QUERY_URI = "/trafficline/index.do?ver=lz&starting=泸州客运中心站&startStationId=646000001&startStationsDisabled=1";
    private static final String TRAFFICLINE_INDEX_URI = "/trafficline/index.do";
    private static final String INDEX_NC_URI = "/indexnc/index.do?ver=nc";
    @Autowired
    private LoginService loginService;
    /**
     * 登录页面
     * @param model
     * @return 登录页面视图名
     */
    @RequestMapping(value="/index")
    public String index(String returnUrl, Model model) {
        model.addAttribute("returnUrl", returnUrl); // NOSONAR
        return "login";
    }
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param returnUrl 返回地址（如果该地址存在，登录成功后会重定向到该地址）
     * @param model 视图model
     * @param response http响应
     * @return
     */
    @RequestMapping(value = "/verify")
    public String verify(String username, String password, String returnUrl, // NOSONAR
                         @CookieValue(value = CookieName.APP_VERSION, defaultValue = WebAppVersion.HX) String appVer,
                         @CookieValue(value = CookieName.OPENID, defaultValue = "") String openid, Model model, HttpServletResponse response) { // NOSONAR
        LoginResultBean loginResult = new LoginResultBean();
        try {
            // 使用用户名和密码登录，获取用户信息
            loginResult = loginService.loginByUsername(username, password);
        } catch (ServiceException e) {
            LOGGER.error("使用用户名和密码登录时发生异常!", e);
            model.addAttribute("msg", "服务器内部错误！"); // NOSONAR
            model.addAttribute("uri", LOGIN_INDEX_URI);
            model.addAttribute("returnUrl", returnUrl);
            return "login_tips"; // NOSONAR
        }

        // 验证登录结果，并做相应的处理
        switch (loginResult.getErrcode()) { // NOSONAR
            case Errcode.SUCCESS: // NOSONAR
                // 记住登录用户
                loginService.rememberLoginUser(loginResult, response);
                LOGGER.debug("用户：{} 已登录成功", username);

                // 执行微信用户和HPE用户的绑定
                try {
                    loginService.addOpenIdBind(loginResult, openid);
                } catch (ServiceException e) {
                    LOGGER.error("微信用户和HPE用户的绑定发生异常!", e);
                }

                // 如果返回地址不存在，登录成功后显示登录提示页面；否则重定向到返回地址
                if (StringUtils.isEmpty(returnUrl)) {
                    if (appVer.equals(WebAppVersion.NC)) {
                        returnUrl = INDEX_NC_URI; // NOSONAR
                    } else if (appVer.equals(WebAppVersion.LZ)) {
                        returnUrl = TRAFFICLINE_QUERY_URI; // NOSONAR
                    } else {
                        returnUrl = TRAFFICLINE_INDEX_URI; // NOSONAR
                    }
                }

                LOGGER.debug("重定向地址：{}", returnUrl);
                try {
                    response.sendRedirect(returnUrl);
                } catch (IOException e) {
                    LOGGER.error("请求重定向时发生IO异常!", e);
                    model.addAttribute("msg", "服务器内部错误！");
                }
                break;
            case Errcode.USERNAME_NOT_FOUND:
                model.addAttribute("msg", "用户名不存在！");
                model.addAttribute("uri", LOGIN_INDEX_URI);
                break;
            case Errcode.PASSWORD_ERROR:
                model.addAttribute("msg", "密码错误！");
                model.addAttribute("uri", LOGIN_INDEX_URI);
                break;
            case Errcode.SERVER_INTERNAL_ERROR:
                model.addAttribute("msg", "服务器内部错误！");
                model.addAttribute("uri", LOGIN_INDEX_URI);
                break;
            default:
                model.addAttribute("msg", "其他错误！");
                model.addAttribute("uri", LOGIN_INDEX_URI);
                break;
        }

        model.addAttribute("returnUrl", returnUrl);
        return "login_tips";
    }

}
